from django.db import models
from django.contrib.auth.models import Permission as DjangoPermission, Group as DjangoGroup
from django.contrib.contenttypes.models import ContentType
from django.utils import timezone
from apps.common.models import TimestampMixin


class PermissionCategory(TimestampMixin):
    """权限分类模型"""

    name = models.CharField(max_length=50, unique=True, verbose_name='分类名称')
    code = models.CharField(max_length=50, unique=True, verbose_name='分类代码')
    description = models.TextField(blank=True, verbose_name='分类描述')
    sort_order = models.IntegerField(default=0, verbose_name='排序')

    class Meta:
        db_table = 'permission_categories'
        verbose_name = '权限分类'
        verbose_name_plural = '权限分类'
        ordering = ['sort_order', 'name']

    def __str__(self):
        return self.name


class PermissionExtension(TimestampMixin):
    """权限扩展模型 - 扩展Django内建Permission"""

    STATUS_CHOICES = [
        ('active', '激活'),
        ('inactive', '禁用'),
    ]

    # 关联Django内建Permission
    permission = models.OneToOneField(
        DjangoPermission,
        on_delete=models.CASCADE,
        verbose_name='Django权限'
    )

    # 扩展字段
    category = models.ForeignKey(
        PermissionCategory,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        verbose_name='权限分类'
    )
    module = models.CharField(max_length=50, verbose_name='所属模块')
    resource_path = models.CharField(max_length=200, blank=True, verbose_name='资源路径')
    frontend_route = models.CharField(max_length=200, blank=True, verbose_name='前端路由')
    api_endpoint = models.CharField(max_length=200, blank=True, verbose_name='API端点')
    description = models.TextField(blank=True, verbose_name='详细描述')
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='active', verbose_name='状态')
    sort_order = models.IntegerField(default=0, verbose_name='排序')

    class Meta:
        db_table = 'permission_extensions'
        verbose_name = '权限扩展'
        verbose_name_plural = '权限扩展'
        ordering = ['sort_order', 'module', 'permission__name']

    def __str__(self):
        return f"{self.module} - {self.permission.name}"

    @property
    def codename(self):
        """获取权限代码名"""
        return self.permission.codename

    @property
    def name(self):
        """获取权限名称"""
        return self.permission.name


class RoleExtension(TimestampMixin):
    """角色扩展模型 - 扩展Django内建Group"""

    STATUS_CHOICES = [
        ('active', '激活'),
        ('inactive', '禁用'),
    ]

    # 关联Django内建Group
    group = models.OneToOneField(
        DjangoGroup,
        on_delete=models.CASCADE,
        verbose_name='Django组'
    )

    # 扩展字段
    code = models.CharField(max_length=50, unique=True, verbose_name='角色代码')
    description = models.TextField(blank=True, verbose_name='角色描述')
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='active', verbose_name='状态')
    is_system = models.BooleanField(default=False, verbose_name='系统角色')
    level = models.IntegerField(default=0, verbose_name='角色级别')
    sort_order = models.IntegerField(default=0, verbose_name='排序')

    class Meta:
        db_table = 'role_extensions'
        verbose_name = '角色扩展'
        verbose_name_plural = '角色扩展'
        ordering = ['sort_order', 'level', 'group__name']

    def __str__(self):
        return self.group.name

    @property
    def name(self):
        """获取角色名称"""
        return self.group.name

    def get_permissions(self):
        """获取角色的所有权限"""
        return self.group.permissions.filter(
            permissionextension__status='active'
        )


class UserRoleAssignment(TimestampMixin):
    """用户角色分配记录"""

    STATUS_CHOICES = [
        ('active', '激活'),
        ('inactive', '禁用'),
        ('expired', '过期'),
    ]

    user = models.ForeignKey('authentication.User', on_delete=models.CASCADE, verbose_name='用户')
    role = models.ForeignKey(RoleExtension, on_delete=models.CASCADE, verbose_name='角色')
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='active', verbose_name='状态')
    assigned_at = models.DateTimeField(auto_now_add=True, verbose_name='分配时间')
    assigned_by = models.ForeignKey(
        'authentication.User',
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='assigned_user_roles',
        verbose_name='分配人'
    )
    expires_at = models.DateTimeField(null=True, blank=True, verbose_name='过期时间')
    reason = models.TextField(blank=True, verbose_name='分配原因')

    class Meta:
        db_table = 'user_role_assignments'
        verbose_name = '用户角色分配'
        verbose_name_plural = '用户角色分配'
        unique_together = ['user', 'role']
        indexes = [
            models.Index(fields=['user', 'status']),
            models.Index(fields=['role', 'status']),
            models.Index(fields=['assigned_at']),
        ]

    def __str__(self):
        return f"{self.user.username} - {self.role.name}"

    def is_active(self):
        """检查分配是否有效"""
        if self.status != 'active':
            return False
        if self.expires_at and self.expires_at < timezone.now():
            return False
        return True
